package me.sdau.spider.openapi.web;

import me.sdau.spider.openapi.comm.aop.LoggerManage;
import me.sdau.spider.openapi.comm.utils.MD5Util;
import me.sdau.spider.openapi.entity.User;
import me.sdau.spider.openapi.exception.AuthException;
import me.sdau.spider.openapi.service.TokenAuthenticationService;
import me.sdau.spider.openapi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

import static me.sdau.spider.openapi.comm.Const.HEADER_STRING;
import static me.sdau.spider.openapi.comm.Const.TOKEN_PREFIX;


@Controller
public class AuthContraller {

    @Autowired
    private TokenAuthenticationService tokenService;
    @Autowired
    private UserService userService;

    @PostMapping("/token")
    @LoggerManage(description = "获取token")
    public ResponseEntity<Map> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User user = Optional
                .ofNullable(userService.getUserByAccount(username))
                .orElseThrow(() -> new AuthException("用户名或密码错误"));
        if (!Objects.equals(user.getAppkey(), MD5Util.encrypt(password, user.getSalt()))) {
            throw new AuthException("用户名或密码错误");
        }
        String str = tokenService.create(user);
        Map<String, String> map = new HashMap<>();
        map.put(HEADER_STRING, TOKEN_PREFIX + str);
        return new ResponseEntity<>(map, HttpStatus.OK);
    }

    @GetMapping(value = {"", "index"})
    public ResponseEntity<String> index() {
        return new ResponseEntity<>("welcome!", HttpStatus.OK);
    }
}
